package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.exception.LogicException;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.util.MD5;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IPermissionService permissionService;

    public PageResult query(QueryObject qo) {
        int rows = employeeMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = employeeMapper.queryForList(qo);
        return new PageResult(rows, result, qo.getCurrentPage(), qo.getPageSize());
    }

    public Employee getById(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(Employee employee, Long[] ids) {
        if (employee.getId() != null) {
            // 更新时删除原来的关系
            employeeMapper.deleteRelation(employee.getId());
            employeeMapper.updateByPrimaryKey(employee);
        } else {
            // 加密密码
            employee.setPassword(MD5.encode(employee.getPassword()));
            employeeMapper.insert(employee);
        }
        // 维护关系


        for (Long id : ids) {
            employeeMapper.insertRelation(employee.getId(), id);

        }
    }

    public void deleteById(Long id) {
        // 维护关系
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    public void login(Employee emp) {
        // 1. 根据用户名查询登录用户
        Employee empInDB = employeeMapper.selectByUsername(emp.getName());
        if (empInDB == null) {
            throw new LogicException("用戶名或密码错误！");
        }

        // 2. 如果用户存在，再比较密码
        String encode = MD5.encode(emp.getPassword());
        if (!empInDB.getPassword().equals(encode)) {
            throw new LogicException("用戶名或密码错误！");
        }
        // 3. 校验通过后，将当前用户保存到session中
        // 将用户保存到session
        UserContext.setCurrentUser(empInDB);
        // 4. 将当前用户的权限表达式放入session
        Set<String> exps = permissionService.getExceptionsByEmpId(empInDB.getId());
        UserContext.setExps(exps);
    }

    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }
}
